﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Reflection;

namespace Fast.Framework
{

    /// <summary>
    /// 动态代理工厂
    /// </summary>
    public static class DynamicProxyFactory
    {

        /// <summary>
        /// 缓存
        /// </summary>
        private static readonly ConcurrentDictionary<string, object> _cache;

        /// <summary>
        /// 构造方法
        /// </summary>
        static DynamicProxyFactory()
        {
            _cache = new ConcurrentDictionary<string, object>();
        }

        /// <summary>
        /// 创建
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="target">目标</param>
        /// <param name="before">前</param>
        /// <param name="after">后</param>
        /// <returns></returns>
        public static T Create<T>(object target, Action<MethodInfo, object[]> before = null, Action<MethodInfo, object[]> after = null)
        {
            var key = typeof(T).GUID.ToString();
            var obj = _cache.GetOrAdd(key, k =>
            {
                return DispatchProxy.Create<T, DynamicProxy<T>>();
            });
            var proxy = obj as DynamicProxy<T>;
            proxy._target = target;
            proxy._before = before;
            proxy._after = after;
            obj = proxy;
            return (T)obj;
        }
    }
}
